<template>
  <el-scrollbar height="calc(100vh - 88px - 40px - 50px)">
    <el-row>
      <!-- 基本信息 -->
      <el-col
        :span="24"
        class="card-box"
        shadow="hover"
      >
        <el-card>
          <el-descriptions
            title="基本信息"
            :column="6"
            border
          >
            <el-descriptions-item label="Redis版本 :">
              {{ cache?.info?.redis_version }}
            </el-descriptions-item>
            <el-descriptions-item label="运行模式 :">
              {{ cache?.info?.redis_mode == 'standalone' ? '单机' : '集群' }}
            </el-descriptions-item>
            <el-descriptions-item label="端口 :">
              {{ cache?.info?.tcp_port }}
            </el-descriptions-item>
            <el-descriptions-item label="客户端数 :">
              {{ cache?.info?.connected_clients }}
            </el-descriptions-item>
            <el-descriptions-item label="运行时间(天) :">
              {{ cache?.info?.uptime_in_days }}
            </el-descriptions-item>
            <el-descriptions-item label="使用内存 :">
              {{ cache?.info?.used_memory_human }}
            </el-descriptions-item>
            <el-descriptions-item label="使用CPU :">
              {{ cache?.info ? parseFloat(cache?.info?.used_cpu_user_children).toFixed(2) : '' }}
            </el-descriptions-item>
            <el-descriptions-item label="内存配置 :">
              {{ cache?.info?.maxmemory_human }}
            </el-descriptions-item>
            <el-descriptions-item label="AOF是否开启 :">
              {{ cache?.info?.aof_enabled == '0' ? '否' : '是' }}
            </el-descriptions-item>
            <el-descriptions-item label="RDB是否成功 :">
              {{ cache?.info?.rdb_last_bgsave_status }}
            </el-descriptions-item>
            <el-descriptions-item label="Key数量 :">
              {{ cache?.dbSize }}
            </el-descriptions-item>
            <el-descriptions-item label="网络入口/出口 :">
              {{ cache?.info?.instantaneous_input_kbps }}kps/
              {{ cache?.info?.instantaneous_output_kbps }}kps
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>
      <!-- 命令统计 -->
      <el-col
        :span="12"
        class="mt-3"
      >
        <el-card
          :gutter="12"
          shadow="hover"
        >
          <div
            ref="commandStatsRef"
            style="width: 100%; height: 420px"
          ></div>
        </el-card>
      </el-col>
      <!-- 内存使用量统计 -->
      <el-col
        :span="12"
        class="mt-3"
      >
        <el-card
          class="ml-3"
          :gutter="12"
          shadow="hover"
        >
          <div
            ref="usedMemoryRef"
            style="width: 100%; height: 420px"
          />
        </el-card>
      </el-col>
    </el-row>
  </el-scrollbar>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, onUnmounted } from 'vue'
import * as RedisApi from '@/api/redis'
import { RedisMonitorInfoVO } from '@/api/redis/types'
import * as echarts from 'echarts'

const cache = ref<RedisMonitorInfoVO>()

// 基本信息
const readRedisInfo = async () => {
  cache.value = await RedisApi.getCache()
}

// 命令统计 ECharts 实例
const commandStatsRef = ref<HTMLElement | null>(null)
let commandChart: echarts.ECharts | null = null

// 内存使用情况 ECharts 实例
const usedMemoryRef = ref<HTMLElement | null>(null)
let usedMemoryChart: echarts.ECharts | null = null

// 内存使用情况
const usedmemoryEchartChika = reactive<any>({
  title: {
    text: '内存使用情况',
    left: 'center',
    show: true,
    offsetCenter: [0, '20%'],
    color: 'yellow',
    fontSize: 20
  },
  toolbox: {
    show: false,
    feature: {
      restore: { show: true },
      saveAsImage: { show: true }
    }
  },
  series: [
    {
      name: '峰值',
      type: 'gauge',
      min: 0,
      max: 50,
      splitNumber: 10,
      color: '#F5C74E',
      radius: '85%',
      center: ['50%', '50%'],
      startAngle: 225,
      endAngle: -45,
      axisLine: {
        lineStyle: {
          color: [
            [0.2, '#7FFF00'],
            [0.8, '#00FFFF'],
            [1, '#FF0000']
          ],
          width: 10
        }
      },
      axisTick: {
        length: 5,
        lineStyle: {
          color: '#76D9D7'
        }
      },
      splitLine: {
        length: 20,
        lineStyle: {
          color: '#76D9D7'
        }
      },
      axisLabel: {
        color: '#76D9D7',
        distance: 15,
        fontSize: 15
      },
      pointer: {
        width: 7,
        show: true
      },
      detail: {
        textStyle: {
          fontWeight: 'normal',
          fontSize: 15,
          color: '#FFFFFF'
        },
        valueAnimation: true
      },
      progress: {
        show: true
      }
    }
  ]
})

// 指令使用情况
const commandStatsRefChika = reactive({
  title: {
    text: '命令统计',
    left: 'center'
  },
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b} : {c} ({d}%)'
  },
  legend: {
    type: 'scroll',
    orient: 'vertical',
    right: 30,
    top: 10,
    bottom: 20,
    data: [] as any[],
    textStyle: {
      color: '#a1a1a1'
    }
  },
  series: [
    {
      name: '命令',
      type: 'pie',
      radius: [20, 120],
      center: ['40%', '60%'],
      data: [] as any[],
      roseType: 'radius',
      label: {
        show: true
      },
      emphasis: {
        label: {
          show: true
        },
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
})

/** 加载数据 */
const getSummary = () => {
  // 初始化命令图表
  initCommandStatsChart()
  usedMemoryInstance()
}

/** 命令使用情况 */
const initCommandStatsChart = async () => {
  if (commandChart) {
    commandChart.dispose()
  }
  commandChart = echarts.init(commandStatsRef.value!)
  commandChart.setOption(commandStatsRefChika)

  try {
    cache.value = await RedisApi.getCache()
    const commandStats = [] as any[]
    const nameList = [] as string[]
    cache.value?.commandStats.forEach(row => {
      commandStats.push({
        name: row.command,
        value: row.calls
      })
      nameList.push(row.command)
    })
    commandStatsRefChika.legend.data = nameList
    commandStatsRefChika.series[0].data = commandStats
    commandChart.setOption(commandStatsRefChika)
  } catch {}
}

const usedMemoryInstance = async () => {
  if (usedMemoryChart) {
    usedMemoryChart.dispose()
  }

  // 等待数据加载完成
  cache.value = await RedisApi.getCache()

  // 动态设置最大值
  usedmemoryEchartChika.series[0].max =
    parseFloat(cache.value!.info.maxmemory_human.replace(/[^\d.]/g, '')) || 100

  await nextTick() // 确保DOM更新
  usedMemoryChart = echarts.init(usedMemoryRef.value!)

  // 设置数据
  usedmemoryEchartChika.series[0].data = [
    {
      value: parseFloat(cache.value!.info.used_memory_human.replace(/[^\d.]/g, '')),
      name: '内存消耗'
    }
  ]

  usedMemoryChart.setOption(usedmemoryEchartChika)
}

/** 初始化 **/
onMounted(() => {
  // 读取 redis 信息
  readRedisInfo()
  // 加载数据
  getSummary()
})

// 清理图表实例
onUnmounted(() => {
  if (commandChart) {
    commandChart.dispose()
  }
  if (usedMemoryChart) {
    usedMemoryChart.dispose()
  }
})
</script>

<style lang="scss" scoped>
.card-box {
  margin-bottom: 20px;
}
</style>
